import { Body, Controller, Get, Post, UnauthorizedException, ForbiddenException } from '@nestjs/common';
import { AuthService, LoginDto, Public, CurrentUser } from '@app/auth';
import { UsersService } from '../services/users.service';
import { 
  ApiTags,
  ApiOperation,
  ApiBody,
  ApiOkResponse,
  ApiUnauthorizedResponse,
  ApiForbiddenResponse,
  ApiBearerAuth
} from '@nestjs/swagger';

@ApiTags('认证')
@Controller('auth')
export class AuthController {
  constructor(
    private readonly authService: AuthService,
    private readonly usersService: UsersService,
  ) {}

  @Public()
  @Post('login')
  @ApiOperation({
    summary: '用户登录',
    description: '使用用户名或邮箱与密码登录，返回访问令牌与刷新令牌。'
  })
  @ApiBody({
    type: LoginDto,
    examples: {
      byUsername: {
        summary: '用户名登录',
        value: { usernameOrEmail: 'admin', password: 'kvadmin123' },
      },
      byEmail: {
        summary: '邮箱登录',
        value: { usernameOrEmail: 'admin@example.com', password: 'kvadmin123' },
      },
    },
  })
  @ApiOkResponse({
    description: '登录成功',
    schema: {
      type: 'object',
      properties: {
        code: { type: 'number', example: 200 },
        data: {
          type: 'object',
          properties: {
            tokens: {
              type: 'object',
              properties: {
                accessToken: { type: 'string', example: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...' },
                refreshToken: { type: 'string', example: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...' },
              },
            },
            user: {
              type: 'object',
              properties: {
                id: { type: 'number', example: 1 },
                username: { type: 'string', example: 'admin' },
                email: { type: 'string', example: 'admin@example.com' },
                roles: { type: 'array', items: { type: 'string' }, example: ['admin'] },
                primaryRole: { type: 'string', example: 'admin' },
              },
            },
          },
        },
        message: { type: 'string', example: '登录成功' },
      },
    },
  })
  @ApiUnauthorizedResponse({ description: '用户名或密码错误' })
  @ApiForbiddenResponse({ description: '用户被禁用' })
  async login(@Body() body: LoginDto) {
    const user = await this.usersService.findByUsernameOrEmail(body.usernameOrEmail);

    if (!user) {
      throw new UnauthorizedException('用户名或密码错误');
    }

    const passwordOk = await this.authService.comparePassword(body.password, user.password);
    if (!passwordOk) {
      throw new UnauthorizedException('用户名或密码错误');
    }

    if (user.status === 0) {
      throw new ForbiddenException('用户已被禁用');
    }

    const primaryRole = user.primaryRole || 'user';
    const tokenPair = await this.authService.generateTokens({
      sub: user.id,
      username: user.username,
      email: user.email,
      role: primaryRole,
    });

    return {
      code: 200,
      data: {
        tokens: tokenPair,
        user: {
          id: user.id,
          username: user.username,
          email: user.email,
          roles: user.roleNames,
          primaryRole,
        },
      },
      message: '登录成功',
    };
  }

  @Get('profile')
  @ApiBearerAuth()
  @ApiOperation({ summary: '获取当前登录用户信息' })
  @ApiOkResponse({
    description: '获取成功',
    schema: {
      type: 'object',
      properties: {
        code: { type: 'number', example: 200 },
        data: {
          type: 'object',
          properties: {
            sub: { type: 'number', example: 1 },
            username: { type: 'string', example: 'admin' },
            email: { type: 'string', example: 'admin@example.com' },
            role: { type: 'string', example: 'admin' },
            iat: { type: 'number', example: 1710000000 },
            exp: { type: 'number', example: 1710864000 },
          },
        },
        message: { type: 'string', example: '获取成功' },
      },
    },
  })
  async profile(@CurrentUser() user: any) {
    return {
      code: 200,
      data: user,
      message: '获取成功',
    };
  }
}



